package com.rdc.example.dao.impl;

import com.rdc.example.entity.VerificationCode;

import java.sql.*;

import static com.rdc.example.util.DBUtil.closeResources;
import static com.rdc.example.util.DBUtil.getConnection;

public class VerificationCodeDaoImpl implements com.rdc.example.dao.VerificationCodeDao {

    @Override
    public boolean insert(VerificationCode verificationCode) throws Exception {
        Connection conn = null;
        PreparedStatement pstmt = null;
        try {
            // 获取连接
            conn = getConnection();
            String sql = "insert into `verification_code` (user_id, content, type, end_at) values (?,?,?,?);";
            // 执行 sql 语句
            pstmt = conn.prepareStatement(sql);
            // 设值
            setVerificationCode(pstmt, verificationCode);
            // 以影响行数 row 判断并返回插入结果
            int row = pstmt.executeUpdate();
            return row > 0;
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            // 释放资源
            closeResources(null, pstmt, conn);
        }
    }

    @Override
    public VerificationCode getByCode(String code) throws Exception {
        // 进行数据库查询操作
        Connection conn = getConnection();
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        VerificationCode verificationCode = null;
        try {
            //0 管理员验证码  1新用户验证码
            String sql = "select * from `verification_code` where content = ?";
            // 执行 sql 语句
            pstmt = conn.prepareStatement(sql);
            // 设值
            pstmt.setString(1, code);
            rs = pstmt.executeQuery();
            // 封装 VerificationCode 数据
            if (rs.next()) {
                verificationCode = getVerificationCode(rs);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            closeResources(rs, pstmt, conn);
        }
        return verificationCode;
    }

    @Override
    public VerificationCode getByCode(String code, Integer type) throws Exception {
        // 进行数据库查询操作
        Connection conn = getConnection();
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        VerificationCode verificationCode = null;
        try {
            String sql = "select * from `verification_code` where content = ? and type = ? ";
            // 执行 sql 语句
            pstmt = conn.prepareStatement(sql);
            // 设值
            pstmt.setString(1, code);
            pstmt.setInt(2, type);
            rs = pstmt.executeQuery();
            // 封装 VerificationCode 数据
            if (rs.next()) {
                verificationCode = getVerificationCode(rs);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            closeResources(rs, pstmt, conn);
        }
        return verificationCode;
    }

    @Override
    public boolean useVerificationCode(String code) throws Exception {
        Connection conn = null;
        PreparedStatement pstmt = null;
        try {// 获取数据库连接
            conn = getConnection();
            //  is_used 字段设为 1
            String sql = "update verification_code set is_used = 1 where content = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, code);
            // 执行更新操作，返回受影响的行数
            int rows = pstmt.executeUpdate();
            // 如果受影响的行数大于 0，说明更新成功，返回 true
            return rows > 0;
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            closeResources(null,pstmt, conn);
        }
    }




    private VerificationCode getVerificationCode(ResultSet rs) throws SQLException {
        VerificationCode verificationCode = new VerificationCode();
        verificationCode.setId(rs.getInt("id"));
        verificationCode.setUserId(rs.getInt("user_id"));
        verificationCode.setContent(rs.getString("content"));
        verificationCode.setType(rs.getInt("type"));
        verificationCode.setIsUsed(rs.getInt("is_used"));
        Timestamp createdAt = rs.getTimestamp("created_at");
        if (createdAt != null) {
            verificationCode.setCreatedAt(createdAt.toLocalDateTime());
        }
        Timestamp endAt = rs.getTimestamp("end_at");
        if (endAt != null) {
            verificationCode.setEndAt(endAt.toLocalDateTime());
        }
        return verificationCode;
    }

    private void setVerificationCode(PreparedStatement pstmt, VerificationCode verificationCode) throws SQLException {
        if (verificationCode.getUserId() != null) {
            pstmt.setInt(1, verificationCode.getUserId());
        } else {
            pstmt.setNull(1, java.sql.Types.INTEGER);
        }
        if (verificationCode.getContent() != null) {
            pstmt.setString(2, verificationCode.getContent());
        } else {
            pstmt.setNull(2, java.sql.Types.VARCHAR);
        }
        if (verificationCode.getType() != null) {
            pstmt.setInt(3, verificationCode.getType());
        } else {
            pstmt.setNull(3, java.sql.Types.INTEGER);
        }
        if (verificationCode.getEndAt() != null) {
            pstmt.setTimestamp(4, Timestamp.valueOf(verificationCode.getEndAt()));
        } else {
            pstmt.setNull(6, java.sql.Types.TIMESTAMP);
        }
    }
}
